package rabbitmq.workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import rabbitmq.common.Const;

/**
 * @author zss
 * @date 2021/8/27 14:30
 * @Email:451682479@qq.com
 */
public class WorkQueueReceiverMain {

    private final static String QUEUE_NAME = "work_queue1";
    private final static String VIRTUAL_HOST = "devHost";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Const.host);
        factory.setUsername(Const.username);
        factory.setPassword(Const.password);
        factory.setVirtualHost(VIRTUAL_HOST);

        String virtualHost = factory.getVirtualHost();

        System.out.println("virtualHost = " + virtualHost);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
            try {
                doWork(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        boolean autoAck = true; // acknowledgment is covered below
        channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {
        });
    }

    private static void doWork(String task) throws InterruptedException {
        Thread.sleep(1000);
        System.out.println(task);
    }
}
